package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

//@ControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
//@ResponseBody
@Slf4j //日志记录
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
//集中处理所有异常
public class GulimallExceptionControllerAdvice {

    //当指定的Controller抛出异常时会被这个类接收并统一处理；
    //@ExceptionHandler指定能处理那些异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
      //控制台打印日志
      log.error("数据校验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        Map<String, String> errorMap = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach((item)->{
            errorMap.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VAILDE_EXCEPTIPN.getCode(), BizCodeEnum.VAILDE_EXCEPTIPN.getMsg())
                .put("data",errorMap);
    }


    //Throwable类是Java语言中所有错误和异常的超类
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        log.error("错误：",throwable);
        return R.error(BizCodeEnum.UNKOWN_EXCEPTION.getCode(), BizCodeEnum.UNKOWN_EXCEPTION.getMsg());
    }

}
